import { useQuasar } from 'quasar';

/* 工具函数, 简单封装一下常用的 */
export function useYuan() {
  const { notify, dialog } = useQuasar();

  /* 内部使用 */
  const common = (
    msg: string,
    type: 'positive' | 'negative' | 'warning' | 'info' | 'ongoing',
    endFn = () => {
      return;
    },
  ) => {
    return notify({
      actions: [{ icon: 'close', color: 'white' }],
      position: 'top',
      message: msg,
      progress: true,
      type: type,
      timeout: 1500,
      onDismiss: () => {
        endFn();
      },
    });
  };

  /* 成功 */
  const Ok = (
    msg = '成功',
    endFn = () => {
      return;
    },
  ) => {
    return common(msg, 'positive', endFn);
  };
  /* 错误 */
  const Fail = (
    msg = '错误',
    endFn = () => {
      return;
    },
  ) => {
    return common(msg, 'negative', endFn);
  };
  /* 警告 */
  const Warn = (
    msg = '警告',
    endFn = () => {
      return;
    },
  ) => {
    return common(msg, 'warning', endFn);
  };

  /* 详情通知 */
  const Info = (
    msg = '详情',
    endFn = () => {
      return;
    },
  ) => {
    return common(msg, 'info', endFn);
  };

  /*类似原生Alert*/
  const Alert = (
    msg = '确认操作?',
    OKFn = () => {
      return;
    },
  ) => {
    dialog({
      title: '提示',
      cancel: false,
      persistent: true,
      message: msg,
    }).onOk(() => {
      OKFn();
    });
  };
  /*类似原生Confirm*/
  const Confirm = (msg = '确认操作?', OKFn: () => void) => {
    dialog({
      title: '提示',
      message: msg,
      cancel: true,
      persistent: true,
    }).onOk(() => {
      OKFn();
    });
  };

  /*类似原生Prompt*/
  const Prompt = (
    title = '提示',
    msg = '请输入',
    OkFn: (data: string) => void,
    modelValue = '',
  ) => {
    dialog({
      title: title,
      message: msg,
      prompt: {
        model: modelValue,
        isValid: (val) => val.length > 0, // << here is the magic
        type: 'text',
      },
      cancel: true,
      persistent: true,
    }).onOk((data: string) => {
      OkFn(data);
    });
  };

  /* 处理数字 */
  const handleNum = (num: number) => {
    if (num > 1000) {
      return (num / 1000).toFixed(1) + 'k';
    }
    return num + '';
  };

  return {
    Ok,
    Fail,
    Warn,
    Info,
    Alert,
    Confirm,
    Prompt,
    handleNum,
  };
}
